package com.lefevre.cms.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.lefevre.cms.bean.MediaInfo;
import com.lefevre.cms.bean.setting.SystemSetting;
import com.lefevre.cms.bean.topic.*;
import com.lefevre.cms.bean.user.AccessUser;
import com.lefevre.cms.bean.user.ResourceEnum;
import com.lefevre.cms.bean.user.User;
import com.lefevre.cms.bean.user.UserGrade;
import com.lefevre.cms.common.ApiResult;
import com.lefevre.cms.mapper.TopicMapper;
import com.lefevre.cms.service.setting.SettingService;
import com.lefevre.cms.service.topic.CommentService;
import com.lefevre.cms.service.topic.TagService;
import com.lefevre.cms.service.topic.TopicService;
import com.lefevre.cms.service.user.UserGradeService;
import com.lefevre.cms.utils.JsonUtils;
import com.lefevre.cms.web.action.TextFilterManage;
import com.lefevre.cms.web.action.common.CaptchaManage;
import com.lefevre.cms.web.action.fileSystem.FileManage;
import com.lefevre.cms.web.action.lucene.TopicLuceneManage;
import com.lefevre.cms.web.action.mediaProcess.MediaProcessQueueManage;
import com.lefevre.cms.web.action.setting.SettingManage;
import com.lefevre.cms.web.action.topic.CommentManage;
import com.lefevre.cms.web.action.topic.TopicManage;
import com.lefevre.cms.web.action.user.UserManage;
import com.lefevre.cms.web.action.user.UserRoleManage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@Api(tags = "话题处理器")
@RestController
@RequestMapping("/topic")
public class TopicController {

    @Resource
    private TopicMapper topicMapper;

    @Resource
    private TopicService topicService;
    @Resource
    private TagService tagService;
    @Resource
    private CommentService commentService;
    @Resource
    private TextFilterManage textFilterManage;
    @Resource
    private CommentManage commentManage;
    @Resource
    private CaptchaManage captchaManage;
    @Resource
    private SettingService settingService;
    @Resource
    private SettingManage settingManage;
    @Resource
    private TopicManage topicManage;
    @Resource
    private TopicLuceneManage topicLuceneManage;
    @Resource
    private UserManage userManage;
    @Resource
    private UserGradeService userGradeService;
    @Resource
    private UserRoleManage userRoleManage;
    @Resource
    private FileManage fileManage;
    @Resource
    private MediaProcessQueueManage mediaProcessQueueManage;


    @GetMapping("/list")
    @ApiOperation(value = "话题分页列表")
    private ApiResult<Object> list(@RequestParam(required = false) Long tagId,
                                   @RequestParam(defaultValue = "1", required = false) Integer page,
                                   @RequestParam(defaultValue = "10", required = false) Integer limit,
                                   @RequestParam(required = false) Map<String, Object> runtimeParameter) {

        AccessUser accessUser = null;
        //获取运行时参数
        if (runtimeParameter != null && runtimeParameter.size() > 0) {
            for (Map.Entry<String, Object> paramIter : runtimeParameter.entrySet()) {
                if ("accessUser".equals(paramIter.getKey())) {
                    accessUser = (AccessUser) paramIter.getValue();
                }
            }
        }

        LambdaQueryWrapper<Topic> wrapper = new LambdaQueryWrapper<>();
        if (tagId != null) {
            wrapper.eq(Topic::getTagId, tagId);
        }
        wrapper.eq(Topic::getStatus, 20);
        wrapper.orderByDesc(Topic::getSort);
        wrapper.orderByDesc(Topic::getPostTime);
        Page<Topic> topicPage = topicMapper.selectPage(new Page<>(page, limit), wrapper);

        List<Topic> topicList = topicPage.getRecords();
        if (topicList != null && topicList.size() > 0) {
            SystemSetting systemSetting = settingService.findSystemSetting_cache();
            for (Topic topic : topicList) {
                //处理视频播放器标签
                if (!StrUtil.isBlank(topic.getContent())) {
                    //处理富文本路径
                    topic.setContent(fileManage.processRichTextFilePath(topic.getContent(), "topic"));
                    Integer topicContentUpdateMark = topicManage.query_cache_markUpdateTopicStatus(topic.getId(), Integer.parseInt(RandomStringUtils.randomNumeric(8)));
                    //生成处理'视频播放器'Id
                    String processVideoPlayerId = mediaProcessQueueManage.createProcessVideoPlayerId(topic.getId(), topicContentUpdateMark);
                    //处理视频信息
                    List<MediaInfo> mediaInfoList = mediaProcessQueueManage.query_cache_processVideoInfo(topic.getContent(), processVideoPlayerId, topic.getTagId(), systemSetting.getFileSecureLinkSecret());
                    topic.setMediaInfoList(mediaInfoList);
                }
            }

            //查询标签名称
            List<Tag> tagList = tagService.findAllTag_cache();
            //标签角色名称 key:标签Id value:角色名称集合
            Map<Long, List<String>> tagRoleNameMap = new HashMap<>();
            //用户角色名称 key:用户名称Id value:角色名称集合
            Map<String, List<String>> userRoleNameMap = new HashMap<>();
            //用户如果对话题项是否有查看权限  key:标签Id value:是否有查看权限
            Map<Long, Boolean> userViewPermissionMap = new HashMap<>();

            if (tagList != null && tagList.size() > 0) {
                for (Topic topic : topicList) {
                    //解析隐藏标签
                    Map<Integer, Object> analysisHiddenTagMap = topicManage.query_cache_analysisHiddenTag(topic.getContent(), topic.getId());
                    if (analysisHiddenTagMap != null && analysisHiddenTagMap.size() > 0) {
                        //内容含有隐藏标签类型
                        //key:内容含有隐藏标签类型  10.输入密码可见  20.评论话题可见  30.达到等级可见 40.积分购买可见 50.余额购买可见  value:当前用户是否已对隐藏内容解锁
                        LinkedHashMap<Integer, Boolean> hideTagTypeMap = new LinkedHashMap<>();
                        //允许可见的隐藏标签
                        List<Integer> visibleTagList = this.getVisibleTagList(accessUser, topic);

                        //按枚举类的顺序排序
                        for (HideTagType hideTagType : HideTagType.values()) {
                            for (Map.Entry<Integer, Object> entry : analysisHiddenTagMap.entrySet()) {
                                if (entry.getKey().equals(hideTagType.getName())) {
                                    if (visibleTagList.contains(entry.getKey())) {
                                        hideTagTypeMap.put(entry.getKey(), true);
                                    } else {
                                        hideTagTypeMap.put(entry.getKey(), false);
                                    }
                                    break;
                                }
                            }
                        }
                        topic.setHideTagTypeMap(hideTagTypeMap);
                    }
                    topic.setIpAddress(null);
                    topic.setContent(null);
                    //会员
                    if (!topic.getIsStaff()) {
                        userRoleNameMap.put(topic.getUserName(), null);
                    }
                    for (Tag tag : tagList) {
                        if (topic.getTagId().equals(tag.getId())) {
                            topic.setTagName(tag.getName());
                            tagRoleNameMap.put(tag.getId(), null);
                            userViewPermissionMap.put(tag.getId(), null);
                            break;
                        }
                    }
                    // 图片处理
                    if (topic.getImage() != null && !"".equals(topic.getImage().trim())) {
                        List<ImageInfo> imageInfoList = JsonUtils.toGenericObject(topic.getImage().trim(), new TypeReference<List<ImageInfo>>() {
                        });
                        if (imageInfoList != null && imageInfoList.size() > 0) {
                            for (ImageInfo imageInfo : imageInfoList) {
                                imageInfo.setPath(fileManage.fileServerAddress() + imageInfo.getPath());
                            }
                            topic.setImageInfoList(imageInfoList);
                        }
                    }
                }
            }
            if (tagRoleNameMap.size() > 0) {
                for (Map.Entry<Long, List<String>> entry : tagRoleNameMap.entrySet()) {
                    List<String> roleNameList = userRoleManage.queryAllowViewTopicRoleName(entry.getKey());
                    entry.setValue(roleNameList);
                }
            }
            if (userRoleNameMap.size() > 0) {
                for (Map.Entry<String, List<String>> entry : userRoleNameMap.entrySet()) {
                    List<String> roleNameList = userRoleManage.queryUserRoleName(entry.getKey());
                    entry.setValue(roleNameList);
                }
            }
            if (userViewPermissionMap.size() > 0) {
                for (Map.Entry<Long, Boolean> entry : userViewPermissionMap.entrySet()) {
                    //是否有当前功能操作权限
                    boolean flag = userRoleManage.isPermission(ResourceEnum._1001000, entry.getKey());
                    entry.setValue(flag);
                }
            }
            for (Topic topic : topicList) {
                if (!topic.getIsStaff()) {//会员
                    User user = userManage.query_cache_findUserByUserName(topic.getUserName());
                    if (user != null) {
                        topic.setNickname(user.getNickname());
                        topic.setAvatarPath(fileManage.fileServerAddress() + user.getAvatarPath());
                        topic.setAvatarName(user.getAvatarName());
                    }

                }
                //话题允许查看的角色名称集合
                for (Map.Entry<Long, List<String>> entry : tagRoleNameMap.entrySet()) {
                    if (entry.getKey().equals(topic.getTagId())) {
                        List<String> roleNameList = entry.getValue();
                        if (roleNameList != null && roleNameList.size() > 0) {
                            topic.setAllowRoleViewList(roleNameList);
                        }
                        break;
                    }
                }
                //用户角色名称集合
                for (Map.Entry<String, List<String>> entry : userRoleNameMap.entrySet()) {
                    if (entry.getKey().equals(topic.getUserName())) {
                        List<String> roleNameList = entry.getValue();
                        if (roleNameList != null && roleNameList.size() > 0) {
                            topic.setUserRoleNameList(roleNameList);
                        }
                        break;
                    }
                }
                //用户如果对话题项无查看权限，则不显示摘要、图片、视频
                for (Map.Entry<Long, Boolean> entry : userViewPermissionMap.entrySet()) {
                    if (entry.getKey().equals(topic.getTagId())) {
                        if (entry.getValue() != null && !entry.getValue()) {
                            topic.setImage(null);
                            topic.setImageInfoList(new ArrayList<>());
                            topic.setSummary("");
                            topic.setMediaInfoList(new ArrayList<>());
                        }
                        break;
                    }
                }
            }
        }
        return ApiResult.success(topicPage);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "查看话题详情")
    public ApiResult<Object> getTopicById(@PathVariable Long id) {
        Topic topic = topicMapper.selectById(id);
        if (ObjectUtils.isEmpty(topic)) {
            return ApiResult.failure("话题不存在");
        }
        return ApiResult.success(topic);
    }

    /**
     * 允许可见的隐藏标签
     */
    private List<Integer> getVisibleTagList(AccessUser accessUser, Topic topic) {
        //允许可见的隐藏标签
        List<Integer> visibleTagList = new ArrayList<>();
        if (accessUser != null) {
            //如果话题由当前用户发表，则显示全部隐藏内容
            if (!topic.getIsStaff() && topic.getUserName().equals(accessUser.getUserName())) {
                visibleTagList.add(HideTagType.PASSWORD.getName());
                visibleTagList.add(HideTagType.COMMENT.getName());
                visibleTagList.add(HideTagType.GRADE.getName());
                visibleTagList.add(HideTagType.POINT.getName());
                visibleTagList.add(HideTagType.AMOUNT.getName());
            } else {
                //解析隐藏标签
                Map<Integer, Object> analysisHiddenTagMap = topicManage.query_cache_analysisHiddenTag(topic.getContent(), topic.getId());
                for (Map.Entry<Integer, Object> entry : analysisHiddenTagMap.entrySet()) {

                    if (entry.getKey().equals(HideTagType.PASSWORD.getName())) {//输入密码可见
                        //话题取消隐藏Id
                        String topicUnhideId = topicManage.createTopicUnhideId(accessUser.getUserId(), HideTagType.PASSWORD.getName(), topic.getId());

                        TopicUnhide topicUnhide = topicManage.query_cache_findTopicUnhideById(topicUnhideId);

                        if (topicUnhide != null) {
                            visibleTagList.add(HideTagType.PASSWORD.getName());//当前话题已经取消隐藏
                        }
                    } else if (entry.getKey().equals(HideTagType.COMMENT.getName())) {//评论话题可见
                        Boolean isUnhide = topicManage.query_cache_findWhetherCommentTopic(topic.getId(), accessUser.getUserName());
                        if (isUnhide) {
                            visibleTagList.add(HideTagType.COMMENT.getName());//当前话题已经取消隐藏
                        }
                    } else if (entry.getKey().equals(HideTagType.GRADE.getName())) {//超过等级可见
                        User _user = userManage.query_cache_findUserByUserName(accessUser.getUserName());
                        if (_user != null) {
                            List<UserGrade> userGradeList = userGradeService.findAllGrade_cache();//取得用户所有等级
                            if (userGradeList != null && userGradeList.size() > 0) {
                                for (UserGrade userGrade : userGradeList) {
                                    if (_user.getPoint() >= userGrade.getNeedPoint() && (Long) entry.getValue() <= userGrade.getNeedPoint()) {
                                        visibleTagList.add(HideTagType.GRADE.getName());//当前话题已经取消隐藏

                                        break;
                                    }
                                }


                            }
                        }

                    } else if (entry.getKey().equals(HideTagType.POINT.getName())) {//积分购买可见
                        //话题取消隐藏Id
                        String topicUnhideId = topicManage.createTopicUnhideId(accessUser.getUserId(), HideTagType.POINT.getName(), topic.getId());

                        TopicUnhide topicUnhide = topicManage.query_cache_findTopicUnhideById(topicUnhideId);

                        if (topicUnhide != null) {
                            visibleTagList.add(HideTagType.POINT.getName());//当前话题已经取消隐藏
                        }
                    } else if (entry.getKey().equals(HideTagType.AMOUNT.getName())) {//余额购买可见
                        //话题取消隐藏Id
                        String topicUnhideId = topicManage.createTopicUnhideId(accessUser.getUserId(), HideTagType.AMOUNT.getName(), topic.getId());
                        TopicUnhide topicUnhide = topicManage.query_cache_findTopicUnhideById(topicUnhideId);

                        if (topicUnhide != null) {
                            visibleTagList.add(HideTagType.AMOUNT.getName());//当前话题已经取消隐藏
                        }
                    }

                }
            }
        }
        return visibleTagList;
    }

}
